package cn.schoolwow.ams.test.config.flow;

import cn.schoolwow.ams.test.entity.FlowLog;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSON;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

public class SetFlowLog implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        //记录流程日志
        FlowLog flowLog = new FlowLog();
        flowLog.setFlowId(flowContext.getId());
        flowLog.setName(flowContext.getFlowName());
        //保存请求数据
        {
            Map<String,Object> requestDataMap = flowContext.getRequestDataMap();
            flowLog.setRequestData(JSON.parseObject(JSON.toJSONString(requestDataMap)));
        }
        //保存流程执行数据
        {
            Map<String,Object> flowExecuteDataMap = flowContext.getFlowExecuteDataMap();
            flowLog.setContextData(JSON.parseObject(JSON.toJSONString(flowExecuteDataMap)));
        }
        //保存流程全局数据
        {
            Map<String,Object> contextDataMap = flowContext.getContextDataMap();
            flowLog.setQuickFlowData(JSON.parseObject(JSON.toJSONString(contextDataMap)));
        }
        //保存流程配置数据
        {
            Map<String,Object> flowConfigDataMap = flowContext.getFlowConfigDataMap();
            flowLog.setFlowConfigData(JSON.parseObject(JSON.toJSONString(flowConfigDataMap)));
        }
        flowLog.setFlowNameList(flowContext.getFlowArray().toJSONString());
        flowLog.setFlowTrace(flowContext.getFlowTrace());
        flowLog.setBrokenReason(flowContext.getBrokenReason());
        Exception e = flowContext.getFlowException();
        if(null!=e){
            flowLog.setException(exception2String(e));
            flowLog.setExceptionMessage(e.getMessage());
        }
        Long startTime = (Long) flowContext.getData("__startTime");
        if(null!=startTime){
            long endTime = System.currentTimeMillis();
            flowLog.setConsumeTime(endTime-startTime);
        }
        flowContext.putTemporaryInstanceData(flowLog);
    }

    @Override
    public String name() {
        return "设置流程日志对象";
    }

    public String exception2String(Exception e) {
        if(null==e){
            return null;
        }
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }
}
